package module

import (
	"strings"

	"gitee.com/liumou_site/logger"
)

// AutomaticCleaning 自动清理
// 1. 清理无效IP记录
// 2. 去除重复记录（相同的IP和域名）
// 3. 确保保留localhost映射
func (h *Hosts) AutomaticCleaning() {
	// 创建map用于去重
	recordMap := make(map[string]bool)
	var validRecords []Record
	hasInvalidIP := false
	hasDuplicates := false
	initialCount := len(h.RecordList)

	// 检查记录并去重
	for _, r := range h.RecordList {
		// 标准化记录格式（忽略大小写）
		ip := strings.TrimSpace(r.Ip)
		domain := strings.ToLower(strings.TrimSpace(r.Domain))

		// 检查IP有效性
		if !isValidIP(ip) {
			logger.Info("清理无效IP记录: ", r.Ip, " ", r.Domain)
			hasInvalidIP = true
			continue
		}

		// 检查域名有效性
		if !isValidHostname(domain) {
			logger.Info("清理无效域名记录: ", r.Ip, " ", r.Domain)
			hasInvalidIP = true
			continue
		}

		// 生成唯一键用于去重
		key := ip + ":" + domain
		if recordMap[key] {
			logger.Info("清理重复记录: ", r.Ip, " ", r.Domain)
			hasDuplicates = true
			continue
		}

		recordMap[key] = true
		validRecords = append(validRecords, Record{Ip: ip, Domain: domain})
	}

	// 确保包含localhost映射
	localhostKey := "127.0.0.1:localhost"
	if !recordMap[localhostKey] {
		logger.Info("添加缺失的localhost映射")
		validRecords = append(validRecords, Record{Ip: "127.0.0.1", Domain: "localhost"})
		hasInvalidIP = true // 标记为需要写入
	}

	// 检查是否有变化
	if !hasInvalidIP && !hasDuplicates && initialCount == len(validRecords) {
		logger.Info("hosts文件已经是最佳状态，无需清理")
		return
	}

	// 更新并保存记录
	h.RecordList = validRecords
	err := h.Write()
	if err != nil {
		logger.Error("清理失败: ", err.Error())
		return
	}

	logger.Info("清理成功")
	logger.Info("原始记录数: ", initialCount, ", 清理后记录数: ", len(validRecords))
	if hasDuplicates {
		logger.Info("清理了重复记录")
	}
	if hasInvalidIP {
		logger.Info("清理了无效IP或域名记录")
	}
}

// CleanAll 清空所有记录
// 保留必要的localhost映射，并确保注释行不受影响
func (h *Hosts) CleanAll() {
	// 清空记录列表但保留注释
	h.RecordList = []Record{
		{Ip: "127.0.0.1", Domain: "localhost"},
		{Ip: "::1", Domain: "localhost"}, // 添加IPv6的localhost映射
	}

	err := h.Write()
	if err != nil {
		logger.Error("清空失败: ", err.Error())
		return
	}

	logger.Info("清空成功，已保留localhost映射")
}
